package tulingxueyuan117;

import com.sun.org.apache.bcel.internal.generic.RET;
import sun.reflect.generics.tree.Tree;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * Author: Zhang Dongwei
 * Date: 2022/11/5 21:15
 * 给你一棵二叉树的根节点 root ，返回其节点值的 后序遍历 。
 */
public class p27_二叉树后序遍历_145 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode node1 = new TreeNode(2);
        TreeNode node2 = new TreeNode(3);
        root.right = node1;
        node1.left = node2;
        List<Integer> res = new ArrayList<>();
        res = postorderTraversal(root);
        System.out.println(res);
    }

//    递归，简单
//    public static List<Integer> postorderTraversal(TreeNode root) {
//        List<Integer> res = new ArrayList<>();
//        accessTree(root, res);
//        return res;
//    }
//    public static void accessTree(TreeNode root, List<Integer> res){
//        if(root == null) return;
//        accessTree(root.left, res);
//        accessTree(root.right, res);
//        res.add(root.val);
//    }

    //    循环迭代
    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        TreeNode prevAccess = null;
        while (root != null || !stack.isEmpty()){
            while (root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if(root.right == null || root.right == prevAccess){
                res.add(root.val);
                prevAccess = root;
                root = null;
            }else {
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }
}
